package com.health.admin.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.health.result.ResultUtils;
import com.health.security.Admin;
import com.health.util.JwtUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;

/**
 * @author: zipeng Li
 * 2021/6/13  15:13
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    @Resource
    ObjectMapper mapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        httpServletResponse.setContentType("application/json;charset=UTF-8");
        ServletOutputStream out = httpServletResponse.getOutputStream();
        //1.获取用户信息
        Admin admin = (Admin)authentication.getPrincipal();
        //2.生成token
        JwtUtils jwtUtils = new JwtUtils();
        String token = jwtUtils.generateToken(admin);

        HashMap<String, Object> map = new HashMap<>(2);
        map.put("token", token);
        map.put("admin", admin);

        String str = mapper.writeValueAsString(ResultUtils.success("认证成功", map));
        out.write(str.getBytes("UTF-8"));
        out.flush();
        out.close();
    }
}
